<template>
	<div class="page-container">
		<el-card class="page-form-card">
			<template v-if="active === 1">
				<el-form ref="form" :rules="rules" :model="form" label-width="95px" :disabled="$route.query.type === 'isAudit'">
					<el-form-item label="商品轮播图: " prop="gallery">
						<span class="create-tips">*商品轮播图 ( 图片要求:宽高相等且大于480px,大小3M内,拖拽可调整顺序。 )</span>
						<l-upload-image ref="gallery" v-model="form.gallery" :cutting="true" height="106px" width="106px" :limit="8" class="w-full mt-[10px]">
							<div class="flex flex-col items-center">
								<svg-icon icon-class="add" size="20px"></svg-icon>
								<el-tooltip effect="dark" content="支持图片类型jpj,png，图片大小不超过4M。" placement="top"> </el-tooltip>
							</div>
						</l-upload-image>
					</el-form-item>
					<el-form-item label="商品名称:" prop="name">
						<el-input v-model.trim="form.name" class="!md:w-[300px]" show-word-limit placeholder="请输入商品名称" />
					</el-form-item>
					<div class="flex">
						<el-form-item label="商品价格:" prop="price">
							<el-input v-model.trim="price" class="!md:w-[300px]" disabled show-word-limit />
						</el-form-item>
						<el-form-item label="供应价格:" prop="supplyPrice">
							<el-input v-model.trim="form.supplyPrice" class="!md:w-[300px]" show-word-limit placeholder="请输入供应价格" @input="changePrice" />
						</el-form-item>
					</div>
					<div class="flex">
						<el-form-item label="售卖截止时间:" prop="saleEndTime">
							<el-date-picker v-model="form.saleEndTime" type="datetime" placeholder="请选择售卖截止时间"> </el-date-picker>
						</el-form-item>
						<el-form-item label="虚拟销量:" prop="expectCommoditySales">
							<el-input v-model.trim="form.expectCommoditySales" class="!md:w-[300px]" show-word-limit placeholder="请输入虚拟销量" />
						</el-form-item>
					</div>
					<div class="flex">
						<el-form-item label="可用时间段:" prop="useTime">
							<el-input v-model.trim="form.useTime" class="!md:w-[300px]" show-word-limit placeholder="请输入用时间段" />
						</el-form-item>
						<el-form-item label="核销时间:" prop="verificationTime">
							<el-input v-model.trim="form.verificationTime" class="!md:w-[300px]" show-word-limit placeholder="请输入核销时间" />
						</el-form-item>
					</div>
					<div class="flex">
						<el-form-item label="套餐分类:">
							<el-select v-model="form.setmealId" placeholder="请选择分类" class="w-[240px]">
								<el-option v-for="(value, index) in goodsTypeList" :key="index" :label="value.name" :value="value.id" />
							</el-select>
						</el-form-item>
						<el-form-item label="库存:" prop="inventory">
							<el-input v-model.trim="form.inventory" class="!md:w-[300px]" show-word-limit placeholder="请输入库存" />
						</el-form-item>
					</div>
					<div class="flex"></div>
					<el-form>
						<el-form-item label="商品详情:">
							<div class="goods-box">
								<div>（详情介绍商品以提升转化。若未编辑，商品发布后轮播图将自动填充至图文详情。）</div>
							</div>
						</el-form-item>
						<el-form-item>
							<!--						<div>（详情介绍商品以提升转化。若未编辑，商品发布后轮播图将自动填充至图文详情。）</div>-->
							<div class="flex mt-[15px] !<sm:flex-wrap">
								<el-card shadow="never" class="!md:w-[283px] w-full <sm:mb-[24px]" :body-style="{ padding: '15px' }">
									<div class="box-preview">
										<div class="title">页面预览</div>
										<div class="content" v-html="content"></div>
									</div>
								</el-card>
								<el-card shadow="never" class="box-preview-edit flex-1 md:ml-[10px]">
									<div class="title">
										<div class="title-name">
											快速编辑
											<span class="tip">（*图片要求：宽高相等且大于480px,大小3M内。拖拽可调整顺序）</span>
										</div>
									</div>
									<div class="mt-[20px]">
										<!--									<vuedraggable-upload-image v-model.trim="previewImgList"></vuedraggable-upload-image>-->
										<Editor v-model="content" :min-height="300" :read-only="$route.query.type === 'isAudit'"> </Editor>
									</div>
								</el-card>
							</div>
						</el-form-item>
					</el-form>
				</el-form>
				<el-card class="page-card">
					<div class="page-card-options">
						<span class="mr-[20px]">套餐详情</span>
						<el-button v-hasPermi="['mall:category:add']" type="primary" @click="handleAdd" :disabled="$route.query.type === 'isAudit'">新增 </el-button>
					</div>
					<el-table v-loading="normsLoading" stripe :data="normsList"  :disabled="$route.query.type === 'isAudit'">
						<el-table-column :formatter="emptyToString" label="序号" align="center" type="index" min-width="120" />
						<el-table-column :formatter="emptyToString" label="名称" align="center" prop="attribute" min-width="120" />
						<el-table-column :formatter="emptyToString" label="单位" align="center" prop="storeUnit" min-width="120" />
						<el-table-column :formatter="emptyToString" label="价格" align="center" prop="supplyPrice" min-width="120" />
						<el-table-column :formatter="emptyToString" label="操作" align="center" class-name="small-padding fixed-width" width="180" fixed="right">
							<template slot-scope="scope">
								<el-button :disabled="$route.query.type === 'isAudit'" type="info" @click="handleNormsUpdate(scope.row, scope.$index)">编辑</el-button>
								<el-button :disabled="$route.query.type === 'isAudit'" type="danger" @click="handleNormsDelete(scope.row, scope.$index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<div v-if="$route.query.type == 'isAudit'" class="op-container">
						<el-button type="primary" class="btn" @click="auditsupplier(1)">通过</el-button>
						<el-button class="btn" @click="digShow">拒绝</el-button>
					</div>
					<div v-else class="op-container">
						<el-button type="primary" class="btn" @click="handlePublish">保存</el-button>
						<el-button class="btn" @click="handleCancel">取消</el-button>
					</div>
				</el-card>
				<el-dialog title="拒绝" :visible.sync="show" width="550px">
					<div class="content">
						<div class="content-info">
							<div class="info info-plus">
								<div>
									<span class="label">拒绝原因：</span
									><span class="text">
										<el-input v-model.trim="audit.auditOpinion" rows="4" maxlength="" placeholder="请输入内容" type="textarea"></el-input>
									</span>
								</div>
							</div>
						</div>
						<div slot="footer" class="dialog-footer mt-[100px]">
							<el-button class="w-[120px] h-[40px]" @click="cancelShow">取 消</el-button>
							<el-button class="w-[120px] h-[40px]" type="primary" @click="auditsupplier(0)">确 认</el-button>
						</div>
					</div>
				</el-dialog>
				<!-- 添加或修改类目对话框 -->
				<el-dialog :title="title" :visible.sync="openNorms" width="500px" append-to-body>
					<el-form ref="normsForm2" :model="normsForm" :rules="normsRules2" label-width="100px">
						<el-form-item label="名称：" prop="attribute">
							<el-input v-model.trim="normsForm.attribute" style="width: 300px" placeholder="请输入名称" />
						</el-form-item>
						<el-form-item label="单位：" prop="storeUnit">
							<el-input v-model.trim="normsForm.storeUnit" style="width: 300px" placeholder="请输入单位" />
						</el-form-item>
						<el-form-item label="原价：" prop="supplyPrice">
							<el-input v-model.trim="normsForm.supplyPrice" style="width: 300px" placeholder="请输入原价" />
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button class="w-[120px] h-[40px]" @click="cancelNorms">取 消</el-button>
						<el-button class="w-[120px] h-[40px]" type="primary" @click="submitNormsForm2">确 认</el-button>
					</div>
				</el-dialog>
			</template>
		</el-card>
	</div>
</template>

<script>
import dayjs from 'dayjs';
import { getToken } from '@/utils/auth';
import Editor from '@/components/Editor';
import vuedraggableUploadImage from '@/components/vuedraggable-upload-image';
import { listParent, listChild } from '@/api/mall/category';
import { addGoods, auditGoods, getInfoGoodsVo, updateGoodsPo } from '@/api/mall/goods';
import { allListTemplate } from '@/api/mall/template';
import { allListZone } from '@/api/mall/zone';
import { allListSelfmention } from '@/api/mall/selfmention';
import clone from 'lodash/clone';
import { allListNorms, delNorms, sortOrderPlus, sortOrderReduce, updateNorms } from '@/api/mall/norms';
import { getAdminSetmealList } from '@/api/mall/mallSetmeal';

export default {
	name: 'Create',
	components: { Editor, vuedraggableUploadImage },
	data() {
		return {
			audit: {
				auditOpinion: null,
			},
			price: '',
			auditRules: {
				auditOpinion: [{ required: true, message: '请输入原因', trigger: 'blur' }],
			},
			mealValue: '',
			content: null,
			active: 1,
			glbVisible: false,
			glbUrl: null,
			oneCate: '',
			twoCate: '',
			imgList: [],
			threeList: [],
			previewImgList: [],
			form: {},
			categoryList: [],
			brandList: [],
			newKeywordVisible: false,
			newKeyword: '',
			keywords: [],
			props: {
				lazy: true,
				expandTrigger: 'click',
				lazyLoad(node, resolve) {
					const { level, value } = node;
					if (level === 0) {
						listParent().then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: false,
							}));
							resolve(nodes);
						});
					} else {
						listChild(value).then((response) => {
							const { data } = response;
							const nodes = data.map((item) => ({
								value: item.id,
								label: item.name,
								leaf: true,
							}));
							resolve(nodes);
						});
					}
				},
			},
			spec: {},
			specifications: [],
			products: [],
			multipleSpec: false,
			productForm: {},
			productVisible: false,
			attributeForm: {},
			attributeVisible: false,
			attributes: [],
			specVisible: false,
			title: '',
			rules: {
				gallery: [{ required: true, message: '请上传商品轮播图', trigger: 'change' }],
				name: [{ required: true, message: '请填写商品名字', trigger: 'blur' }],
				supplyPrice: [{ required: true, message: '请填写供应价格', trigger: 'blur' }],
				deadTime: [{ required: true, message: '请选择售卖截止时间', trigger: 'blur' }],
				virtualSale: [{ required: true, message: '请输入虚拟销量', trigger: 'blur' }],
				activeTime: [{ required: true, message: '请输入用时间段', trigger: 'blur' }],
				cancelTime: [{ required: true, message: '请输入核销时间', trigger: 'blur' }],
			},
			goodsLoading: false,
			gallery: [],
			goodsTypeList: [],
			oneCateList: [],
			twoCateList: [],
			express: {
				expressType: 1,
				expressTelId: null,
			},
			loading: false,
			selecLoading: false,
			templateList: [],
			zoneList: [],
			selfMentionList: [],
			normsLoading: false,
			normsList: [],
			openNorms: false,
			// 表单参数
			normsForm: {
				// supplyPrice: '',
				// attribute: '',
				// inventory: '',
			},
			normsRules2: {
				supplyPrice: [{ required: true, message: '请填写价格', trigger: 'blur' }],
				attribute: [{ required: true, message: '请填写名字', trigger: 'blur' }],
				storeUnit: [{ required: true, message: '请填写单位', trigger: 'blur' }],
			},
			normsTitle: '',
			temporaryId: 0,
			show: false,
		};
	},
	computed: {
		headers() {
			return {
				Authorization: 'Bearer ' + getToken(),
			};
		},
	},
	watch: {
		$route: {
			handler: function () {
				if (this.$route.query.id) {
					this.temporaryId = this.$route.query.id || null;
					this.getNormsList();
				}
			},
			deep: true,
			immediate: true,
		},
	},
	created() {
		this.reset();

		this.casShow = true;
		this.getOneCateList();
		this.getTelList();
		this.getInfo();
		this.category();
		this.getCateList();
		this.getOneCateList();
	},
	methods: {
		getCateList() {
			getAdminSetmealList({}).then((res) => {
				this.goodsTypeList = res.data;
				console.log('999', res);
				// console.log('this.getAdminSetmealList', res.data);
			});
		},
		digShow() {
			this.show = true;
		},
		cancelShow() {
			this.show = false;
		},
		handleAuditSupplier() {
			this.$refs.audit.validate((bool) => {
				if (bool) {
					this.auditSupplier(0);
				}
			});
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.reset();
			this.openNorms = true;
			this.title = '新增';
			this.normsForm = {
				price: '',
				name: '',
				unit: '',
			};
		},
		// 支付价=显示供应价*3
		changePrice() {
			console.log('this.form.supplyPrice', this.form.supplyPrice);
			this.price = this.form.supplyPrice * 2;
		},
		auditSupplier(type) {
			auditGoods({
				id: this.$route.query.id,
				status: type,
				...this.audit,
			}).then(() => {
				this.$message.success('操作成功');
				this.show = false;
				this.$router.back();
			});
		},
		auditSupplierClose() {
			this.$refs.audit.resetFields();
			this.show = false;
		},
		getInfo() {
			if (!this.$route.query.id) return;
			getInfoGoodsVo(this.$route.query.id).then((response) => {
				let { data = {} } = response;
				this.form = {
					...data.mallGoodsVO,
					count: data.mallGoodsVO.memberDiscount !== 0 ? 1 : 0,
				};
				this.threeList = data.mallGoodsVO.threeDUrl ? [data.mallGoodsVO.threeDUrl] : [];
				this.oneCate = data.mallGoodsVO.categoryId && data.mallGoodsVO.categoryId[0];
				let twoCate = data.mallGoodsVO.categoryId && data.mallGoodsVO.categoryId[1];
				// console.log('this.oneCate',data.mallGoodsVO);
				// return;
				listChild(this.oneCate).then((response) => {
					const { data } = response;
					const nodes = data.map((item) => ({
						value: item.id,
						label: item.name,
					}));
					this.twoCateList = nodes;
					this.twoCate = twoCate;
					this.express.expressType = this.form.logisticsId;
					this.express.expressTelId = this.form.templateId;
				});
				this.content = this.form.detail;
				this.form.gallery = data.mallGoodsVO.gallery ? JSON.parse(data.mallGoodsVO.gallery) : [];
				// this.keywords = this.form.keywords.split(',');
				this.getTelList();
				this.changePrice();
			});
			this.reset();
			getAdminSetmealList({}).then((res) => {
				this.goodsTypeList = res.data;
				// console.log('999', res);
				// console.log('this.getAdminSetmealList', res.data);
			});
		},
		/** 搜索商品规格参数列表 */
		getNormsList() {
			this.normsLoading = true;
			allListNorms({ goodsId: this.temporaryId }).then((response) => {
				console.log(response.data, 'response.data');
				this.normsList = response.data;
				this.normsLoading = false;
			});
		},
		// 取消按钮
		cancelNorms() {
			this.openNorms = false;
			// this.resetNorms();
			this.$refs['normsForm'].resetFields();
		},
		// 提交按钮
		// submitNormsForm() {
		// 	this.$refs['normsForm'].validate((valid) => {
		// 		if (valid) {
		// 			if (this.normsForm.id != null) {
		// 				this.openNorms = false;
		// 				updateNorms(this.normsForm).then((response) => {
		// 					this.msgSuccess('编辑成功');
		// 					this.openNorms = false;
		// 					this.getNormsList();
		// 				});
		// 			} else {
		// 				this.msgSuccess('新增成功');
		// 				this.openNorms = false;
		// 				this.normsList.push({ ...this.normsForm });
		// 			}
		// 			console.log(this.normsList);
		// 		}
		// 	});
		// },
		// 表单重置
		resetNorms() {
			console.log(1);
			this.normsForm = {
				id: null,
				goodsId: null,
				attribute: null,
				supplyPrice: null,
				picUrl: null,
				inventory: null,
				counterPrice: null,
				delFlag: null,
				sortOrder: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				tenantId: null,
				threeDUrl: null,
				deductPrice: null,
				storeUnit: null,
			};
			this.resetForm('normsForm');
		},
		handlePreview(url) {
			this.glbUrl = process.env.VUE_APP_MODEL_URL + url;
			this.glbVisible = true;
		},
		/** 新增按钮操作 */
		handleNormsAdd() {
			this.normsForm.id = null;
			this.openNorms = true;
			this.normsTitle = '添加商品规格参数';
		},
		/** 编辑按钮操作 */
		handleNormsUpdate(row, index) {
			if (row.id !== null) {
				this.normsForm.id = index;
			} else {
				this.normsForm.id = row.id;
			}
			this.openNorms = true;
			this.changePrice();
			this.normsTitle = '编辑商品规格参数';
			this.$nextTick(() => {
				this.normsForm = { ...row, idIndex: index };
			});
		},
		/** 删除按钮操作 */
		handleNormsDelete(row, index) {
			this.$confirm('是否确认删除?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			}).then(() => {
				delNorms([row.id]).then((response) => {
					this.normsList.splice(index, 1);
				});
			});
		},
		/** 提交按钮 */
		// submitNormsForm() {
		// 	this.$refs['normsForm'].validate((valid) => {
		// 		if (valid) {
		// 			if (!this.normsForm.picUrl) {
		// 				this.msgError('请上传规格图片');
		// 				return;
		// 			}
		// 			console.log(this.normsForm.id);
		// 			if (this.normsForm.id != null) {
		// 				this.msgSuccess('编辑成功');
		// 				this.openNorms = false;
		// 				Object.keys(this.normsList[this.normsForm.id]).forEach((key) => {
		// 					if (key !== 'id') {
		// 						this.normsList[this.normsForm.id][key] = this.normsForm[key];
		// 					}
		// 				});
		// 			} else {
		// 				this.msgSuccess('新增成功');
		// 				this.openNorms = false;
		// 				this.normsList.push(clone(this.normsForm));
		// 			}
		// 			this.$refs['normsForm'].resetFields();
		// 		}
		// 	});
		// },
		changeExpressTelId(id) {
			this.getZoneList(id);
		},
		changeExpressType(value) {
			if (value != 2) {
				return;
			}
			this.getselfmentionList();
		},
		getselfmentionList() {
			this.loading = true;
			allListSelfmention().then((response) => {
				this.selfMentionList = response.data;
				this.loading = false;
			});
		},
		getTelList() {
			allListTemplate().then((response) => {
				this.templateList = response.data;
				this.express.expressTelId = this.templateList[0].id;
				this.getZoneList(this.templateList[0].id);
			});
		},
		getZoneList(query) {
			this.loading = true;
			allListZone({ templateId: query }).then((response) => {
				this.zoneList = response.data;
				this.loading = false;
			});
		},
		getRandom: function () {
			//随机生成9位
			let random = Math.floor((Math.random() + Math.floor(Math.random() * 8 + 1)) * Math.pow(8, 9));
			if (random.toString().length > 9) {
				random = Math.floor((Math.random() + Math.floor(Math.random() * 8 + 1)) * Math.pow(8, 9));
			}
			return random;
		},
		clearOne() {
			this.twoCate = '';
		},
		oneCateChange(value) {
			// this.twoCateList = []
			if (!value) {
				return;
			}
			this.twoCate = '';
			listChild(value).then((response) => {
				const { data } = response;
				const nodes = data.map((item) => ({
					value: item.id,
					label: item.name,
				}));
				this.twoCateList = nodes;
			});
		},
		getOneCateList() {
			listParent().then((response) => {
				const { data } = response;
				const nodes = data.map((item) => ({
					value: item.id,
					label: item.name,
				}));
				console.log(nodes);
				this.oneCateList = nodes;
			});
		},
		reset() {
			this.form = {
				id: null,
				goodsSn: null,
				name: null, //商品名称
				categoryId: null,
				brandId: null,
				keywords: null,
				brief: null,
				isOnSale: null,
				gallery: [],
				videoUrl: null,
				sortOrder: null,
				picUrl: null,
				shareUrl: null,
				isNew: null,
				isHot: null,
				unit: null,
				counterPrice: null,
				retailPrice: null, //商品价格
				contributionNum: null,
				detail: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				salesDiscount: 8.5,
				commoditySales: 0,
				realSales: 0,
				memberDiscount: null,
				count: 1,
				inventory: '',
				expectCommoditySales: 0,
				isBonus: 1,
			};
			this.spec = { specification: '', value: '', picUrl: '' };
			this.specifications = [{ specification: '规格', value: '标准', picUrl: '' }];
			this.products = [{ id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }];
			this.productForm = {
				id: 0,
				specifications: [],
				price: 0.0,
				number: 0,
				url: '',
			};
			this.resetForm('form');
		},
		uploadPicUrl(res, file) {
			this.form.picUrl = res.url;
		},
		uploadOverrun() {
			this.$message({
				type: 'error',
				message: '上传文件个数超出限制!最多上传5张图片!',
			});
		},
		handleGalleryUrl(res, file) {
			this.gallery.push({ name: res.url, url: res.url });
			this.form.gallery = JSON.stringify(this.gallery.map((item) => item.url));
		},
		handleRemove(file, fileList) {
			this.gallery.slice(
				this.gallery.findIndex((item) => item === file.url),
				1
			);
			this.form.gallery = JSON.stringify(this.gallery.map((item) => item.url));
		},
		showInput() {
			this.newKeywordVisible = true;
			this.$nextTick((_) => {
				this.$refs.newKeywordInput.$refs.input.focus();
			});
		},
		handleInputConfirm() {
			const newKeyword = this.newKeyword;
			if (newKeyword) {
				this.keywords.push(newKeyword);
				this.form.keywords = this.keywords.toString();
			}
			this.newKeywordVisible = false;
			this.newKeyword = '';
		},
		handleClose(tag) {
			this.keywords.splice(this.keywords.indexOf(tag), 1);
			this.goods.keywords = this.keywords.toString();
		},
		uploadSpecPicUrl(res, file) {
			this.spec.picUrl = res.url;
		},
		getTime(startTime, endTime) {
			this.queryParams.startTime = startTime;
			this.queryParams.endTime = endTime;
		},
		handleSpecificationAdd() {
			let index = this.specifications.length - 1;
			for (let i = 0; i < this.specifications.length; i++) {
				const v = this.specifications[i];
				if (v.specification === this.spec.specification) {
					if (v.value === this.spec.value) {
						this.$message({
							type: 'warning',
							message: '已经存在规格值:' + v.value,
						});
						this.spec = {};
						this.specVisible = false;
						return;
					} else {
						index = i;
					}
				}
			}

			this.specifications.splice(index + 1, 0, this.spec);
			this.specVisible = false;
			this.specToProduct();
		},
		handleSpecificationDelete(row) {
			const index = this.specifications.indexOf(row);
			this.specifications.splice(index, 1);
			this.specToProduct();
		},
		specToProduct() {
			if (this.specifications.length === 0) {
				return;
			}
			// 根据specifications创建临时规格列表
			let specValues = [];
			let spec = this.specifications[0].specification;
			let values = [];
			values.push(0);

			for (let i = 1; i < this.specifications.length; i++) {
				const aspec = this.specifications[i].specification;

				if (aspec === spec) {
					values.push(i);
				} else {
					specValues.push(values);
					spec = aspec;
					values = [];
					values.push(i);
				}
			}
			specValues.push(values);

			// 根据临时规格列表生产货品规格
			// 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
			let productsIndex = 0;
			let products = [];
			let combination = [];
			let n = specValues.length;
			for (let s = 0; s < n; s++) {
				combination[s] = 0;
			}
			let index = 0;
			let isContinue = false;
			do {
				let specifications = [];
				for (let x = 0; x < n; x++) {
					let z = specValues[x][combination[x]];
					specifications.push(this.specifications[z].value);
				}
				products[productsIndex] = {
					id: productsIndex,
					specifications: specifications,
					price: 0.0,
					number: 0,
					url: '',
				};
				productsIndex++;

				index++;
				combination[n - 1] = index;
				for (let j = n - 1; j >= 0; j--) {
					if (combination[j] >= specValues[j].length) {
						combination[j] = 0;
						index = 0;
						if (j - 1 >= 0) {
							combination[j - 1] = combination[j - 1] + 1;
						}
					}
				}
				isContinue = false;
				for (let p = 0; p < n; p++) {
					if (combination[p] !== 0) {
						isContinue = true;
					}
				}
			} while (isContinue);

			this.products = products;
		},
		handleSpecificationShow() {
			this.spec = { specification: '', value: '', picUrl: '' };
			this.specVisible = true;
		},
		specChanged(label) {
			if (label === false) {
				this.specifications = [{ specification: '规格', value: '标准', picUrl: '' }];
				this.products = [{ id: 0, specifications: ['标准'], price: 0.0, number: 0, url: '' }];
			} else {
				this.specifications = [];
				this.products = [];
			}
		},
		handleProductShow(row) {
			this.productForm = Object.assign({}, row);
			this.productVisible = true;
		},
		handleProductEdit() {
			for (let i = 0; i < this.products.length; i++) {
				const v = this.products[i];
				if (v.id === this.productForm.id) {
					this.products.splice(i, 1, this.productForm);
					break;
				}
			}
			this.productVisible = false;
		},
		uploadProductUrl(response) {
			this.productForm.url = response.url;
		},
		handleAttributeShow() {
			this.attributeForm = {};
			this.attributeVisible = true;
		},
		handleAttributeAdd() {
			this.attributes.unshift(this.attributeForm);
			this.attributeVisible = false;
		},
		handleAttributeDelete(row) {
			const index = this.attributes.indexOf(row);
			this.attributes.splice(index, 1);
		},
		handleCancel() {
			this.normsList.forEach(function (item) {
				delNorms([item.id]);
			});
			this.$router.push('/goods/goodsStoreList');
		},
		submitNormsForm2() {
			this.$refs['normsForm2'].validate((valid) => {
				if (valid) {
					console.log('valid', valid);
					if (this.normsForm.idIndex != null) {
						this.msgSuccess('编辑成功');
						this.openNorms = false;
						Object.keys(this.normsList[this.normsForm.idIndex]).forEach((key) => {
							this.normsList[this.normsForm.idIndex][key] = this.normsForm[key];
						});
						this.resetNorms();
					} else {
						this.msgSuccess('新增成功');
						this.openNorms = false;
						this.normsList.push({ ...this.normsForm });
					}
					console.log(this.normsList);
				}
			});
		},
		// 通过
		auditsupplier(type) {
			auditGoods({
				auditOpinion: this.auditOpinion,
				id: this.$route.query.id,
				retailPrice: this.price,
				status: type,
			}).then((res) => {
				this.$message.success('操作成功!');
				this.show = false;
				this.$router.push('/goods/goodsStoreList');
			});
		},
		handlePublish() {
			let goods = {
				id: this.$route.query.id, //商品id
				name: this.form.name, //商品名称
				categoryId: this.twoCate, //	一级分类
				chain: 0, //是否供应链商品 1-是 0-否
				expectCommoditySales: this.form.virtualSale, //预计销量
				gallery: JSON.stringify(this.form.gallery), //商品宣传图片列表，采用JSON数组格式
				goodsType: 0, //商品类型
				detail: this.content, //	商品详细介绍，是富文本格式
				inventory: this.form.inventory, //库存
				logisticsId: 0, //物流方式
				retailPrice: this.price, //	零售价格(现价)
				saleEndTime: dayjs(this.form.deadTime).format('YYYY-MM-DD HH:mm:ss'), //截止时间
				verificationTime: this.form.cancelTime, //核销时间
				useTime: this.form.activeTime, //可用时间
				store: 1, //是否是店铺商品
				storeId: this.$route.query.storeId, //店铺id
				supplier: 0, //是否是供应商商品 0 是 1 否
				supplyPrice: this.form.supplyPrice, //供应价
				topCategoryId: this.oneCate, //二级分类
			};
			const resultGoods = {
				goods: goods,
				norms: this.normsList,
			};
			if (this.$route.query.id) {
				updateGoodsPo(resultGoods)
					.then(() => {
						this.$message.success('更新成功');
						this.$router.push('/goods/goodsStoreList');
					})
					.finally(() => {
						this.goodsLoading = false;
					});
			} else {
				addGoods(resultGoods)
					.then(() => {
						this.$message.success('添加成功');
						this.$router.push('/goods/goodsList');
					})
					.finally(() => {
						this.goodsLoading = false;
					});
			}
		},
		handleCategoryChange(value) {
			this.form.categoryId = value[value.length - 1];
		},
		reSortOrderPlus(row) {
			sortOrderPlus({
				id: row.id,
				sortOrder: row.sortOrder,
				goodsId: row.goodsId,
			}).then(() => {
				this.getNormsList();
			});
		},
		reSortOrderReduce(row) {
			sortOrderReduce({
				id: row.id,
				sortOrder: row.sortOrder,
				goodsId: row.goodsId,
			}).then(() => {
				this.getNormsList();
			});
		},
		handleOn() {
			this.active--;
			this.$nextTick(() => {
				this.form.videoUrl && this.$refs.videoUrl.syncElUploads([this.form.videoUrl]);
				this.form.gallery && this.$refs.gallery.syncElUploads(this.form.gallery);
			});
		},
		handleNext() {
			if (this.active === 1) {
				if (!this.oneCate) {
					this.$message.error('请选择一级分类');
					return;
				}
				if (!this.twoCate) {
					this.$message.error('请选择二级分类');
					return;
				}
				this.form.memberDiscount = this.form.count === 1 ? this.form.memberDiscount : 10;
				this.$refs.form.validate((bool) => {
					if (bool) {
						this.active += 1;
					}
				});
			}
		},
		handleNextOne() {
			if (this.normsList.length < 1) {
				this.$message.error('请上传商品规格');
				return;
			}
			this.active += 1;
		},
	},
};
</script>

<style scoped lang="scss">
.steps {
	::v-deep {
		.el-step.is-horizontal .el-step__line {
			top: 22px;
			background-color: rgba(112, 112, 112, 0.2);
			height: 1px;
		}
		.el-step__icon {
			width: 46px;
			height: 46px;
			border: 1px solid;
		}
		.is-finish {
			.el-step__icon {
				background: var(--primary-color);
				color: #fff;
				font-size: 12px;
			}
		}
		.el-step__title.is-wait {
			border-color: #999999;
			color: #999999;
		}
		.is-process {
			border-color: #999999;
			color: #999999;
			font-weight: normal;
			.el-step__icon {
				font-size: 12px;
			}
		}
	}
}
.card {
	::v-deep {
		.el-card__header {
			padding: 0 0 12px 0;
		}
	}
}

.content {
	::v-deep {
		img {
			width: 100%;
		}
	}
}
//分割线
.expressZoneDiv {
	//height: 500px;
}
.selfmentionDiv {
	height: 500px;
	margin: 15px 0px;
}
::v-deep.avatar-box .el-card__body {
	padding-right: 0 !important;
}
.box-preview-edit {
	width: 800px;
	min-height: 500px;
	.title {
		border-bottom: 1px solid #f7f7f7;
		width: 100%;
		color: #2c333f;
		.tip {
			color: #f14a46;
			font-size: 10px;
		}
	}
}

.box-preview {
	height: 600px;

	//padding: 0 15px;
	/*padding: 0 15px;*/
	/*padding-top: 10px;*/
	ul {
		padding: 0;
		margin: 0;
		list-style: none;
		overflow-y: scroll;
		min-width: 242px;
		height: 570px;
		li {
			img {
				display: block;
				width: 242px;
				height: 242px;
			}
		}
	}
	.title {
		border-bottom: 1px solid #f7f7f7;
		width: 100%;
		height: 43px;
		line-height: 43px;
		color: #2c333f;
	}
}
.op-container {
	display: flex;
	justify-content: center;
	margin-top: 10px;
	.btn {
		width: 236px;
		height: 60px;
		border: 1px solid #707070;
		opacity: 1;
		padding: 0;
		line-height: 60px;
		text-align: center;
		border-radius: 4px;
		font-size: 18px;
	}
}
.text {
	font-size: 14px;
}

.item {
	padding: 18px 0;
}

.input-new-keyword {
	width: 90px;
	margin-left: 10px;
	vertical-align: bottom;
}

.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}

.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 150px;
	height: 150px;
	line-height: 150px;
	text-align: center;
}

.avatar {
	width: 178px;
	height: 178px;
	display: block;
}
.create-tips {
	color: red;
	font-size: 12px;
}
.create-select {
	width: 300px;
}
.goods-box {
	margin-left: 0;
}
.goods-detail {
	display: flex;
	flex-wrap: wrap;
	min-width: 1100px;
}
::v-deep .picker {
	bottom: -20px !important;
}
.page-preview {
	::v-deep .el-form-item__content {
		margin-left: 0 !important;
	}
}
.page-card {
	::v-deep .el-card__body {
		padding: 0 !important;
	}
}
::v-deep .el-dialog__body {
	display: flex;
	align-items: center;
	justify-content: center;
}
.content {
	.content-info {
		.image__preview {
			display: flex;
			justify-content: center;
			.image {
				width: 329px;
				height: 162px;
				margin: 0 10px;
				display: block;
				border-radius: 8px;
			}
		}
		.info {
			display: flex;
			margin-bottom: 25px;

			> div {
				width: 50%;
				height: 40px;
				line-height: 40px;
				display: flex;
				color: #333333;
				justify-content: center;
				.label {
					width: 85px;
					font-size: 12px;
				}
				.text {
					width: 225px;
					//background: #F7F7F7;
					font-size: 14px;
					box-sizing: border-box;
					padding-left: 12px;
				}
			}
		}
		.info-plus {
			> div {
				width: 100%;
				.text {
					width: 303px;
				}
			}
		}
	}
}
</style>
